package com.example.forceoffline;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import java.util.prefs.PreferenceChangeEvent;

public class LoginActivity extends BaseActivity {
    private EditText accountEdit;
    private EditText passwordEdit;
    private Button login;

    private CheckBox checkBox;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        accountEdit = (EditText) findViewById(R.id.account);
        passwordEdit = (EditText) findViewById(R.id.password);
        login = (Button) findViewById(R.id.login);
        checkBox = findViewById(R.id.remember_me);
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        String account = "";
        String password = "";
        boolean remember_me = pref.getBoolean("remember_me", false);
        if (remember_me){
             account = pref.getString("account", "");
             password = pref.getString("password", "");
        }
        accountEdit.setText(account);
        passwordEdit.setText(password);
        checkBox.setChecked(remember_me);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String account = accountEdit.getText().toString();
                String password = passwordEdit.getText().toString();
                //如果账号是admin且密码是123456，就认为登录成功
                if (account.equals("admin") && password.equals("123456")) {
                    SharedPreferences.Editor edit = pref.edit();
                    if (checkBox.isChecked()){
                        edit.putString("account", account);
                        edit.putString("password", password);
                        edit.putBoolean("remember_me", true);
                    }else{
                        edit.clear();
                    }
                    edit.apply();
                    Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                }else {
                    Toast.makeText(LoginActivity.this,"account or password is invalid",Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}